package servlet;

import bean.Message;
import bean.PageBean;
import bean.UserInfo;
import dao.DeptMajorDao;
import dao.MessageDao;
import dao.UserDao;
import dao.UserInfoDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.RequestUtil;
import util.ResponseUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 用户身份验证
 *
 * @author 邓晴予
 */
public class UserInfoServlet extends HttpServlet {
    private DeptMajorDao deptMajorDao = new DeptMajorDao();
    private UserInfoDao userInfoDao = new UserInfoDao();
    private UserDao userDao = new UserDao();
    private MessageDao messageDao = new MessageDao();

    /**
     * 骑行用户提出身份验证申请
     * 即向userInfo表中添加一条数据
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserInfo userInfo = new UserInfo();
        userInfo.setStuId(req.getParameter("studentId"));
        userInfo.setName(req.getParameter("name"));
        userInfo.setSchool(req.getParameter("school"));
        userInfo.setUserId(req.getParameter("userId"));
        String major = req.getParameter("major");
        String dept = req.getParameter("department");
        JsonWrapper result = new JsonWrapper();

        boolean belong = deptMajorDao.isMajorBelongDept(major, dept);
        if (belong) {
//			专业属于院系
            try {
                userInfo.setMajor(major);
//				添加userInfo记录
                boolean isScucess = userInfoDao.insertUserInfo(userInfo);
                if (isScucess) {
//					添加成功
                    result.setStatus(200);
                    result.setMsg("success");
                } else {
//					添加失败
                    result.setStatus(404);
                    result.setMsg("add failed");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                result.setStatus(401);
                result.setMsg("exception happened");
            }
        } else {
//			专业不属于院系
            result.setStatus(404);
            result.setMsg("invalid major or dept");
        }
        ResponseUtil.write(resp, result.get());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String t = req.getParameter("t");
        String startStr = req.getParameter("start");
        String pagesizeStr = req.getParameter("pagesize");
        JsonWrapper result = new JsonWrapper();
        int start = 0;
        int pagesize = 0;
        try {
            if (!StringUtil.isEmpty(startStr)) {
                start = Integer.parseInt(startStr);
            }
            if (!StringUtil.isEmpty(pagesizeStr)) {
                pagesize = Integer.parseInt(pagesizeStr);
            }
            PageBean pageBean = new PageBean(start, pagesize);
            if ("requests".equals(t)) {
//				获取新申请
                try {
                    JSONArray jsonArray = userInfoDao.getAllUserInfo(pageBean);
                    result.setDataJsonArray("values", jsonArray);
                    result.setStatus(200);
                    result.setMsg("success");
                } catch (Exception e) {
                    e.printStackTrace();
                    result.setStatus(401);
                    result.setMsg("query failed");
                }
            }
        } catch (NumberFormatException exp) {
//			查询失败
            result.setStatus(404);
            result.setMsg("number cast failed");
        }
        ResponseUtil.write(resp, result.get());
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject jo = RequestUtil.getJsonFromRequest(req);

        String userInfoId = jo.getString("userInfoId");
        String userId = jo.getString("userId");
        String action = jo.getString("action");
        JsonWrapper result = new JsonWrapper();

        if ("true".equals(action)) {
//			身份验证通过
//			更新user的userInfoId
            userDao.changeUserInfoId(userId, userInfoId);
//			更新user的name
            userDao.changeName(userId, userInfoId);

            userInfoDao.deleteUserId(userInfoId);
            try {
                messageDao.messageAdd(new Message(null, "1", userId, "恭喜您，管理员已通过您的身份验证申请！", null, null));
                result.setStatus(200);
                result.setMsg("success");
            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(401);
                result.setMsg("failed");
            }
        } else if ("false".equals(action)) {
//			身份验证未通过
//			删除userInfo
            userInfoDao.deleteUserInfo(userInfoId);
            try {
                messageDao.messageAdd(new Message(null, "1", userId, "很遗憾，管理员未通过您的身份验证申请。", null, null));
                result.setStatus(200);
                result.setMsg("success");
            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(401);
                result.setMsg("exception happeded");
            }
        }
        ResponseUtil.write(resp, result.get());
    }
}
